package android.Spider;

import android.app.Activity;
import android.content.Context;
import android.database.Cursor;
import android.provider.Contacts;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CursorAdapter;
import android.widget.Filterable;
import android.widget.TextView;

public class ContactListAdapter extends CursorAdapter implements Filterable
{

    public ContactListAdapter(Cursor c, Activity context) {
        super(c, context);
        m_activity = context;
    }

    @Override
    public View newView(Context context, Cursor cursor, ViewGroup parent) {
        TextView view = new TextView(context);
        view.setText(convertToString(cursor));
        return view;
    }

    @Override
    public void bindView(View view, Context context, Cursor cursor) {
        ((TextView)view).setText(convertToString(cursor));
    }

    @Override
    protected String convertToString(Cursor cursor) {
    	final int nNameIndex = cursor.getColumnIndex(Contacts.ContactMethods.NAME);
    	final int nEmailIndex = cursor.getColumnIndex(Contacts.ContactMethods.DATA);
    	String str = cursor.getString(nNameIndex) + "<" + cursor.getString(nEmailIndex) + ">";
        return str;
    }

    @Override
    protected Cursor runQuery(CharSequence constraint)
    {
    	String strQuery = constraint == null ? "" : constraint.toString();
    	int nLast = strQuery.lastIndexOf(",");
    	if (nLast != -1)
    	{
        	strQuery = strQuery.substring(nLast + 1);
        	strQuery = strQuery.trim();
    	}

        Cursor cursor = m_activity.managedQuery(
        		Contacts.ContactMethods.CONTENT_URI, 
        		PROJECTION, 
        		(strQuery.length() == 0) ? null : "UPPER(" + Contacts.ContactMethods.NAME + ") GLOB ?",
        		new String[] { "*" + strQuery.toUpperCase() + "*" }, 
        		null); 

        return cursor;
    }

    private Activity m_activity;
    
	static String[] PROJECTION = new String[] { 
        Contacts.ContactMethods.NAME,
        Contacts.ContactMethods.DATA,
        Contacts.ContactMethods._ID,
        Contacts.ContactMethods.KIND
    }; 

}
